package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.adapter.MyNewsHomeAdapter;
import com.sczmgk.hotline_pzh.base.RefreshAndLoadMoreBaseActivity;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.callback.VerfyCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.InformationTitleDaoImpl;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.IndicatorInfos;
import com.sczmgk.hotline_pzh.entity.InformationBean;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.SecurityCodeUtils;
import com.sczmgk.hotline_pzh.view.NoDoubleItemClickListener;
import com.sczmgk.hotline_pzh.view.RefreshListView;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.ScrollIndicatorView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2016/12/7 0007.
 */
public class MyCollectionActivity extends RefreshAndLoadMoreBaseActivity<InformationBean> {

    /*访问网络成功后发送的指示器消息*/
    private static final int INDICATOR_REFRESH = 103;
    private static final int REQUEST_CODE = 201;

//    /*新闻的type*/
//    private static final int NEWS = 1;
//    /*公告的type*/
//    private static final int NOTICE = 2;
//    /*指南的type*/
//    private static final int GUIDE = 3;

//    /*带有下拉刷新的ListView*/
//    private RefreshListView mListView;

    /*顶部指示器Indicator*/
    private ScrollIndicatorView mSivIndicator;

    /*指示器信息的集合*/
    private List<IndicatorInfos> indicatorInfos = new ArrayList<>();

    /*空白的图片的控件*/
    private LinearLayout mLayoutEmpty;

    /*判断是否是第一次进入*/
    private boolean isFirstIn = true;

    /*搜索框*/
    private LinearLayout mSeachBar;

    private MyNewsHomeAdapter newsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_conllect);
        indicatorInfos = InformationTitleDaoImpl.getIntance(MyCollectionActivity.this).findAll();
        setHeader();

        initView();

        initData();

        setListener();
    }

    /**
     * 设置标题栏
     */
    private void setHeader() {
        setTitle(R.string.my_collection);
        setLeftBtnVisibility(View.VISIBLE);
        setHeadBackgroudColor(Color.WHITE);
        setTitleColor(Color.BLACK);
    }

    /**
     * 初始化控件
     */
    private void initView() {

        //下拉刷新的listview
        mListView = (RefreshListView) findViewById(R.id.lv_comllection);
        //空图片的控件
        mLayoutEmpty = (LinearLayout) findViewById(R.id.ll_collection_empty);
        //添加indicator
        mSivIndicator = (ScrollIndicatorView) findViewById(R.id.siv_indicator);
        //搜索框
        mSeachBar = (LinearLayout) findViewById(R.id.ll_collection_search);
        if (indicatorInfos != null && indicatorInfos.size() > 0) {
            setIndicator(getIndicatorTitles());
        }
    }

    /**
     * 设置指示器
     *
     * @param indicatorTitle 指示器的标题
     */
    public void setIndicator(String[] indicatorTitle) {
        //设置Indicator指示器
        mSivIndicator.setBackgroundResource(R.color.white);
        CommonUtils.setIndector(mSivIndicator, indicatorTitle, MyCollectionActivity.this);
    }

    /**
     * 初始化数据
     */
    private void initData() {

        //设置收藏信息的Adapter
        newsAdapter = new MyNewsHomeAdapter(MyCollectionActivity.this, lists);
        mListView.setAdapter(newsAdapter);

        loadingDialog = DialogFactory.getLoadingDialog(MyCollectionActivity.this) ;
        DialogFactory.showDialog(loadingDialog);

        //获取指示器的信息
        SecurityCodeUtils.getIndicatorData(this, new VerfyCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError(BaseEntity.MyError mError) {

            }

            @Override
            public void onLoadIndicatorDataCallback(List<IndicatorInfos> lists) {

                if (indicatorInfos == null){
                    indicatorInfos = new ArrayList<>() ;
                }

                if (indicatorInfos.size() > 0) {
                    indicatorInfos.clear();
                }

                indicatorInfos.addAll(lists);

                mHandler.sendEmptyMessage(INDICATOR_REFRESH);
            }
        });
    }


    /**
     * 设置监听
     */
    @Override
    public void setListener() {
        super.setListener();

        //指示器的监听
        mSivIndicator.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View view, int position, int i1) {
                //根据指示器的类型访问网络

                if (lists.size() > 0) {
                    lists.clear();
                    newsAdapter.notifyDataSetChanged();
                }

                if (mLayoutEmpty.getVisibility() == View.VISIBLE) {
                    mLayoutEmpty.setVisibility(View.GONE);
                }

                if (mListView.isRefresh()){
                    mListView.hideHeaderView();
                }

                loadData(1, "", LOAD_NORMAL);
            }
        });

        //listview的条目点击事件
        mListView.setOnItemClickListener(new NoDoubleItemClickListener() {
            @Override
            public void NoDoubleItemClickListener(AdapterView<?> parent, View view, int i, long id) {
                int position = i - 1;
                //跳转传递url和标题
                InformationBean informationBean = lists.get(position);
                Intent intent = new Intent(MyCollectionActivity.this, NewsDetailActivity.class);
                intent.putExtra(Constants.NEWS_DETAIL_ITEM, informationBean);
//                intent.putExtra(Constants.MY_COLLECTION_FLAG, Constants.MY_COLLECTION_FLAG_INFO);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        //listview长按删除功能
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                //弹出删除提示框dialog
                showDeleteDialog(i - 1);

                return true;
            }
        });

        //搜索框的点击事件
        mSeachBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyCollectionActivity.this , SearchActivity.class) ;
                intent.putExtra("type" , -1) ;
                intent.putExtra(Constants.SEARCH_MODULE_TITLE , "收藏") ;
                startActivityForResult(intent ,REQUEST_CODE);
            }
        });
    }

    @Override
    public Map<String, Object> getRequestData(int page, String keyword) {
        int item = mSivIndicator.getCurrentItem();
        int type = indicatorInfos.get(item).type;
        Map<String, Object> infos = new HashMap<>();
        infos.put("type", type);
        infos.put("userid", CacheUtils.getIntData(MyCollectionActivity.this, Constants.LOGIN_UID, 0));
        infos.put("imei", MyApp.imei);
        infos.put("page", page);

        return infos;
    }

    @Override
    public String getRquestUrl() {
        return Constants.BASE_URL + Constants.GET_MY_COLLECTION_URL;
    }

    @Override
    public int getListType() {
        return LIST_TYPE_UP_LOAD_MORE;
    }
//
//    private String getInformationTypeName(){
//       int curentItem = mSivIndicator.getCurrentItem();
//        return indicatorInfos.get(curentItem).title;
//    }

    /**
     * 展示长按删除的dialog
     */
    private void showDeleteDialog(final int position) {

        DialogFactory.chooseDialog(MyCollectionActivity.this, R.string.delete_collection_des, R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 长按删除收藏的消息,暂时直接弹出框从集合删除
                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("userid", CacheUtils.getIntData(MyCollectionActivity.this, Constants.LOGIN_UID, 0));
                maps.put("newsid", lists.get(position).id);
                MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_DELECT_COLLECTION, maps, MyHttp.POST, MyCollectionActivity.this, false, null, new SimplePaserJsonCallback() {
                    @Override
                    public void onVerifyIsNull() {
                        lists.remove(position);
//                        newsAdapter.notifyDataSetChanged();
                        mHandler.sendEmptyMessage(REFRESH_LIST) ;
                    }

                    @Override
                    public void onVerifySuccess(String dataRaw, boolean isCache) {
                        lists.remove(position);
//                        newsAdapter.notifyDataSetChanged();
                        mHandler.sendEmptyMessage(REFRESH_LIST) ;
                    }

                    @Override
                    public void onErrorCodeError(BaseEntity.MyError mError) {
                        super.onErrorCodeError(mError);
                        DialogFactory.warningDialog(MyCollectionActivity.this, mError.msg);
                    }
                });

            }
        });
    }


    /**
     * 设置空的图片的显示,dialog的显示,刷新的显示
     */
    public void setDialogVisiable(int emptyVisiable) {

        //设置图片的显示
        mLayoutEmpty.setVisibility(emptyVisiable);

        //关闭加载dialog
//        if (loadingDialog != null) {
//            DialogFactory.dismissLoadingDialog(loadingDialog);
//        }

        //如果是正在刷新,隐藏头部局,展示内容
        if (mListView.isRefresh()) {
            mListView.hideHeaderView();
        }
        isFirstIn = false;
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {

            case REFRESH_LIST:

                //刷新收藏ListView
                if (lists.size() > 0) {
                    mLayoutEmpty.setVisibility(View.GONE);
                    mListView.setEnablePullDown(true);
                } else {
                    mLayoutEmpty.setVisibility(View.VISIBLE);
                    mListView.setEnablePullDown(false);
                }

                newsAdapter.notifyDataSetChanged();
                break;
            case INDICATOR_REFRESH:

                //设置指示器
                if (indicatorInfos.size() > 0) {
                    setIndicator(getIndicatorTitles());
                    loadData(1, "", LOAD_NORMAL);
                }

                break;
        }
    }

    @Override
    public boolean getIsNeedLogin() {
        return true;
    }

    public String[] getIndicatorTitles() {
        if (indicatorInfos == null || indicatorInfos.size() == 0) {
            return new String[0];
        }
        String[] indicatorTitle = new String[indicatorInfos.size()];
        for (int i = 0; i < indicatorInfos.size(); i++) {
            IndicatorInfos indicator = indicatorInfos.get(i);
            indicatorTitle[i] = indicator.title;
        }
        return indicatorTitle;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                if (mListView != null && mListView.isRefresh()){
                    mListView.hideHeaderView();
                }
                loadData(1, "", LOAD_NORMAL);
            }
        }

    }
}
